<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品ID" prop="productId">
        <el-input
            v-model="queryParams.productId"
            placeholder="请输入商品ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺ID" prop="storeId">
        <el-input
            v-model="queryParams.storeId"
            placeholder="请输入店铺ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退货原因" prop="returnReason">
        <el-input
            v-model="queryParams.returnReason"
            placeholder="请输入退货原因"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['sale:returns:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['sale:returns:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['sale:returns:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['sale:returns:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退货记录ID" align="center" prop="id" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="店铺ID" align="center" prop="storeId" />
      <el-table-column label="退货原因" align="center" prop="returnReason" />
      <el-table-column label="时间戳" align="center" prop="timestamp" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.timestamp, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除标记" align="center" prop="deleted" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sale:returns:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sale:returns:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改店铺退货记录表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="returnsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="店铺ID" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入店铺ID" />
        </el-form-item>
        <el-form-item label="退货原因" prop="returnReason">
          <el-input v-model="form.returnReason" placeholder="请输入退货原因" />
        </el-form-item>
        <el-divider content-position="center">商品详细信息的信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddItemInformation">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteItemInformation">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="itemInformationList" :row-class-name="rowItemInformationIndex" @selection-change="handleItemInformationSelectionChange" ref="itemInformation">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商品名称" prop="productName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="类别ID" prop="categoryId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.categoryId" placeholder="请输入类别ID" />
            </template>
          </el-table-column>
<!--          <el-table-column label="体积" prop="volume" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.volume" placeholder="请输入体积" />
            </template>
          </el-table-column>-->
<!--          <el-table-column label="制造商" prop="manufacturer" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.manufacturer" placeholder="请输入制造商" />
            </template>
          </el-table-column>-->
          <el-table-column label="有效期" prop="expiryDate" width="240">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.expiryDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择有效期">
              </el-date-picker>
            </template>
          </el-table-column>
<!--          <el-table-column label="进货价格" prop="purchasePrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.purchasePrice" placeholder="请输入进货价格" />
            </template>
          </el-table-column>
          <el-table-column label="销售价格" prop="sellingPrice" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.sellingPrice" placeholder="请输入销售价格" />
            </template>
          </el-table-column>-->
          <el-table-column label="创建时间" prop="createdAt" width="240">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.createdAt"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择创建时间">
              </el-date-picker>
            </template>
          </el-table-column>
<!--          <el-table-column label="更新时间" prop="updatedAt" width="240">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.updatedAt"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择更新时间">
              </el-date-picker>
            </template>
          </el-table-column>-->
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Returns">
import { listReturns, getReturns, delReturns, addReturns, updateReturns } from "@/api/sale/returns";

const { proxy } = getCurrentInstance();

const returnsList = ref([]);
const itemInformationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedItemInformation = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    storeId: null,
    returnReason: null,
  },
  rules: {
    productId: [
      { required: true, message: "商品ID不能为空", trigger: "blur" }
    ],
    storeId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    returnReason: [
      { required: true, message: "退货原因不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询店铺退货记录表列表 */
function getList() {
  loading.value = true;
  listReturns(queryParams.value).then(response => {
    returnsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productId: null,
    storeId: null,
    returnReason: null,
    timestamp: null,
    deleted: null
  };
  itemInformationList.value = [];
  proxy.resetForm("returnsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加店铺退货记录表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReturns(_id).then(response => {
    form.value = response.data;
    itemInformationList.value = response.data.itemInformationList;
    open.value = true;
    title.value = "修改店铺退货记录表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["returnsRef"].validate(valid => {
    if (valid) {
      form.value.itemInformationList = itemInformationList.value;
      if (form.value.id != null) {
        updateReturns(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReturns(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除店铺退货记录表编号为"' + _ids + '"的数据项？').then(function() {
    return delReturns(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 存储商品详细信息的序号 */
function rowItemInformationIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 存储商品详细信息的添加按钮操作 */
function handleAddItemInformation() {
  let obj = {};
  obj.productName = "";
  obj.categoryId = "";
  obj.weight = "";
  obj.volume = "";
  obj.manufacturer = "";
  obj.expiryDate = "";
  obj.purchasePrice = "";
  obj.sellingPrice = "";
  obj.createdAt = "";
  obj.updatedAt = "";
  itemInformationList.value.push(obj);
}

/** 存储商品详细信息的删除按钮操作 */
function handleDeleteItemInformation() {
  if (checkedItemInformation.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的存储商品详细信息的数据");
  } else {
    const itemInformations = itemInformationList.value;
    const checkedItemInformations = checkedItemInformation.value;
    itemInformationList.value = itemInformations.filter(function(item) {
      return checkedItemInformations.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleItemInformationSelectionChange(selection) {
  checkedItemInformation.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sale/returns/export', {
    ...queryParams.value
  }, `returns_${new Date().getTime()}.xlsx`)
}

getList();
</script>
